<template>
  <div class="product-add" v-loading="loading">
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="基础设置" name="basic"></el-tab-pane>
      <el-tab-pane label="商品详情" name="content"></el-tab-pane>
      <el-tab-pane label="地区设置" name="area"></el-tab-pane>
      <el-tab-pane label="规格库存" name="spec"></el-tab-pane>
    </el-tabs>
    <!--form表单-->
    <el-form size="small" ref="form" :model="form" label-width="180px">
      <!--基础信息-->
      <Basic v-show="activeName == 'basic'"></Basic>
      <!--规格设置-->
      <Spec v-show="activeName == 'spec'"></Spec>
      <!--商品详情-->
      <Content v-show="activeName == 'content'"></Content>
      <!--地区设置-->
      <AreaSet v-show="activeName == 'area'"></AreaSet>
      <!--高级设置-->
      <!-- <Buyset v-show="activeName == 'buyset'"></Buyset>
      <Others v-show="activeName == 'others'"></Others> -->
      <!--提交-->
      <div class="common-button-wrapper">
        <el-button size="small" type="info" @click="cancelFunc" icon="Back">取消返回</el-button>
        <el-button size="small" type="primary" @click="onSubmit('edit')" :disabled="save_loading" icon="Promotion">提交保存</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import PorductApi from "@/api/product.js";
import Basic from "./part/Basic.vue";
import Spec from "./part/Spec.vue";
import Content from "./part/Content.vue";
import Buyset from "./part/Buyset.vue";
import { formatModel } from "@/utils/base.js";
import Others from "./part/Others.vue";
import AreaSet from "./part/AreaSet.vue";

export default {
  components: {
    /*基础信息*/
    Basic,
    /*规格信息*/
    Spec,
    /*商品详情*/
    Content,
    /*高级设置*/
    Buyset,
    Others,
    AreaSet
  },
  data() {
    return {
      activeName: "basic",
      /*商品ID*/
      productId: 0,
      /*判断是编辑*/
      scene: "edit",
      /*是否正在加载*/
      loading: true,
      /*是否正在提交保存*/
      save_loading: false,
      /*form表单数据*/
      form: {
        model: {},
        /*商品分类*/
        category: [],
        /*运费模板*/
        delivery: [],
        /*会员等级*/
        gradeList: [],
        produceAddrList: [],//生产基地
        /*规格数据*/
        specData: null,
        /*是否锁住*/
        isSpecLocked: false,
        /*万能表单*/
        tableList: [],
      },
      /*模型数据*/
      model: {
        customForm: [],
        tableList: [],
        /*商品名称*/
        productName: "",
        productNo: "",
        videoId: 0,
        videoFilePath: "",
        posterId: 0,
        posterFilePath: "",
        /*商品分类*/
        categoryId: null,
        /*商品图片*/
        image: [],
        modelId: '',
        modelName: '',
        areaList: [],
        areaCity: [],//省市区


        isPicture: 0,
        contentImage: [],
        /*商品卖点*/
        sellingPoint: "",
        /*规格类别,默认10单规格，20多规格*/
        specType: 10,
        /*库存计算方式,默认20付款减库存，10下单减库存*/
        deductStockType: 20,
        /*检查用户等级*/
        isAloneGrade: 0,
        /*单规格*/
        sku: {
          /*产品价格*/
          productPrice: 0,
          /*产品划线价*/
          linePrice: 0,
          /*库存数量*/
          stockNum: 0,
          /*商品重量*/
          productWeight: 0,
          /*商品编码*/
          productNo: "",
        },
        /*多规格类别*/
        specMany: {
          /*多规格类别*/
          specAttr: [],
          /*多规格表格数据*/
          specList: [],
        },
        /*商品详情内容*/
        content: "",
        /*运费模板ID*/
        deliveryId: "",
        /*商品状态*/
        productStatus: 10,
        /*初始销量*/
        salesInitial: 0,
        /*商品排序，默认100*/
        productSort: 100,
        /*是否开启积分赠送,默认1为开启，0为关闭*/
        isPointsGift: 1,
        /*是否允许使用积分抵扣,默认1为允许，0为不允许*/
        isPointsDiscount: 1,
        /*最大积分抵扣数量*/
        maxPointsDiscount: 0,
        /*会员折扣设置,默认1为单独设置折扣,0为默认折扣*/
        isEnableGrade: 1,
        /*等级金额类型,默认10为百分比，20为固定金额*/
        aloneGradeType: 10,
        /*限购会员*/
        gradeIds: [],
        /*是否虚拟商品*/
        isVirtual: 0,
        /*限购数量*/
        limitNum: 0,
        /*虚拟商品发货方式*/
        virtualAuto: 0,
        /*虚拟商品发货内容*/
        virtualContent: "",
        isPreview: 0,
        /*商品预告时间*/
        previewTime: "",
        /*关联表单*/
        tableId: "",
      },
    };
  },
  provide: function () {
    return {
      form: this.form,
    };
  },
  async created() {
    /*获取列表*/
    this.productId = this.$route.query.productId;
    this.scene = this.$route.query.scene;
    await this.getData();
  },
  methods: {
    /**
     * 获取基础数据
     */
    getData: async function () {
      let self = this;
      PorductApi.getEditData(
        {
          productId: self.productId,
          scene: self.scene,
        },
        true
      )
        .then((res) => {
          if (res && res.code === 1) {
            const { model: data } = res.data
            // 基础数据
            self.form.category = res.data.category
            self.form.model.isSpecLocked = res.data.isSpecLocked
            Object.keys(data).forEach(key => {
              self.form.model[key] = data[key]
            })
            //种类
            self.form.model.categoryParentId = data.categoryParentId
            //品种
            self.form.model.categoryId = data.categoryId
            //商品名称
            self.form.model.productName = data.productName
            //商品类型
            this.form.model.productType = data.productType



            //规格
            self.form.model.spec = data.spec
            self.form.model.modelName = data.spec
            //图集
            self.form.model.image = data.image
            //商品属性
            self.form.model.isVirtual = data.isVirtual
            //排序
            self.form.model.productSort = data.productSort
            //发货时间
            self.form.model.deliveryTime = data.deliveryTime
            //适宜种植时间
            if (data.plantTime) {
              self.form.model.plantTime = data.plantTime
              self.form.model.plantTimeArry = data.plantTime.split('~')
            }
            //定金比例
            self.form.model.depositRatio = data.depositRatio
            // 包装费比例
            self.form.model.packageRatio = data.packageRatio
            //地区
            self.form.model.areaList = []
            if (data.areaCityList && data.areaCityList.length > 0) {
              data.areaCityList.forEach(item => {
                self.form.model.areaList.push({
                  // areaName: [item.province, item.city, item.district],
                  areaName: item.areaName,
                  areaCode: item.areaCode && (item.areaCode.includes(",") && item.areaCode.split(","))
                })
              })
            }
            //规格明细
            self.form.model.specList = []
            if (data.sku && data.sku.length > 0) {
              self.form.model.specList = data.sku.map(f => {
                return {
                  ...f,
                  image: {
                    imageId: f.imageId,
                    filePath: f.imagePath
                  }
                }
              })
            }
            //库存计算方式
            self.form.model.deductStockType = data.deductStockType
            self.form.produceAddrList = res.data.produceAddrList
            //主键
            self.form.model.productId = data.productId
            // 商品详情
            self.form.model.content = data.content
            //设置富文本





          }
          self.loading = false;
          console.log('res', self.form)
        })
        .catch((error) => {
          self.loading = false;
          console.log(error);
        });
    },
    /*转JSON字符串*/
    convertJson(list) {
      let obj = {};
      list.forEach((item) => {
        obj[item.gradeId] = item.productEquity;
      });
      return JSON.stringify(obj);
    },

    /*提交*/
    onSubmit: function (submit_type) {
      let self = this;
      let params = self.form.model;
      self.$refs.form.validate((valid) => {
        if (valid) {
          if (params.areaList && params.areaList.length <= 0) {
            ElMessage.error('请填写地区')
            return false
          }
          var setCount = params.areaList.filter(f => f.areaName)
          if (setCount.length < params.areaList.length) {
            ElMessage.error('请确保每行地区都已填写')
            return false
          }
          if (params.areaList && params.areaList.length > 0) {
            params.areaCity = []
            params.areaList.forEach(item => {
              console.log(item, '890')
              const value = item.areaCode
              params.areaCity.push({
                province: value[0],
                city: value[1],
                district: value[2],
                areaName: item.areaName,
                areaCode: item.areaCode.join(",")
              })
            })
          }

          //检查规格库存
          if (params.specList && params.specList.length <= 0) {
            ElMessage.error('请填写规格库存')
            return
          }
          const colors = []
          let isBreak = false
          if (params.modelName === '农资') {
            params.specList.forEach(color => {
              if (colors.includes(color.type)) {
                ElMessage.error('类型不能重复，已存在相同的类型')
                isBreak = true
                return
              }
              if (!color.image) {
                ElMessage.error('请选择不同规格对应的图片')
                isBreak = true
                return
              }
              colors.push(color.type)
            })
          } else {
            params.specList.forEach(color => {
              if (colors.includes(color.color)) {
                ElMessage.error('颜色不能重复，已存在相同的颜色')
                isBreak = true
                return
              }
              if (!color.image) {
                ElMessage.error('请选择不同规格对应的图片')
                isBreak = true
                return
              }
              colors.push(color.color)
            })
          }

          if (isBreak)
            return
          const newParams = JSON.parse(JSON.stringify(params))
          delete newParams.modelId
          delete newParams.modelName
          delete newParams.areaList
          delete newParams.plantTimeArry
          newParams.gradeIds = ''
          delete newParams.sku
          self.loading = true;
          newParams.scene = 'edit'

          console.log('编辑数据提交', newParams)
          PorductApi.editProduct(newParams, true)
            .then((data) => {
              self.loading = false;
              ElMessage({
                message: "编辑成功",
                type: "success",
              });
              self.$router.push("/product/product/index");

            })
            .catch((error) => {
              self.loading = false;
            });
        }
      });
    },

    /*保存为草稿*/
    Draft() {
      let self = this;
      self.form.model.productStatus = 30;
      self.onSubmit();
    },

    /*取消*/
    cancelFunc() {
      this.$router.back(-1);
    },
  },
};
</script>

<style lang="scss" scoped>
.product-add {
  padding-bottom: 50px;
}
</style>
